package org.jie.guider.maven.codeformatter.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

/**
 * @author LiJie
 */
public class ConfigReaderUtil {

    public static Map<String, String> read(InputStream in)
        throws ParserConfigurationException, SAXException, IOException {

        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser parser = factory.newSAXParser();
        ConfigReaderHandler handler = new ConfigReaderHandler();
        parser.parse(in, handler);
        return handler.getConfig();
    }

    private static class ConfigReaderHandler extends DefaultHandler {

        /**
         * 获取属性的元素
         */
        private static final String ATTR = "setting";
        /**
         * 配置属性
         */
        Map<String, String> config;

        @Override
        public void startDocument() throws SAXException {
            super.startDocument();
            config = new HashMap<>(100);
        }

        @Override
        public void startElement(String uri, String localName, String qName,
                                 Attributes attributes) throws SAXException {

            if (!ATTR.equalsIgnoreCase(qName)) {
                return;
            }
            String id = attributes.getValue(0);
            String value = attributes.getValue(1);
            this.config.put(id, value);
        }

        public Map<String, String> getConfig() {
            return config;
        }
    }
}
